package com.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author Zan
 * @Create 2024/5/7 20:34
 * @ClassName : ReEntryLockDemo
 * @Description : TODO 请用一句话描述该类的功能
 */
public class ReEntryLockDemo {

    public synchronized void m1() {
        // 指的是可重复可递归可调用的锁，在外层使用锁之后，在内存依然可以使用，并且不发生死锁，这样的锁就叫做可重入锁
        System.out.println(Thread.currentThread().getName() + "\t ---- come in");
        m2();
        System.out.println(Thread.currentThread().getName() + "\t ---- end");
    }

    public synchronized void m2() {
        System.out.println(Thread.currentThread().getName() + "\t ---- come in");
        m3();
    }

    private synchronized void m3() {
        System.out.println(Thread.currentThread().getName() + "\t ---- come in");
    }

    static Lock lock = new ReentrantLock();

    public static void main(String[] args) {

        /*ReEntryLockDemo reEntryLockDemo = new ReEntryLockDemo();

        new Thread(() -> {
            reEntryLockDemo.m1();
        }, "t1").start();*/

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t --- come in 外层调用");
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "\t --- come in 内层调用");
                } finally {
                    lock.unlock();
                }
            } finally {
                // 这里故意注释，实现加锁次数和释放次数不一样
                // 由于加锁次数和释放次数不一样，第二个线程始终无法获取到锁，导致一直在等待。
//                lock.unlock(); // 正常情况，加锁几次就要解锁几次
            }
        }, "t1").start();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t --- come in 外层调用");
            } finally {
                lock.unlock();
            }
        }, "t2").start();

    }

    private static void reEntryM1() {
        final Object obj = new Object();

        new Thread(() -> {
            synchronized (obj) {
                System.out.println(Thread.currentThread().getName() + "\t --- 外层调用");
                synchronized (obj) {
                    System.out.println(Thread.currentThread().getName() + "\t --- 中层调用");
                    synchronized (obj) {
                        System.out.println(Thread.currentThread().getName() + "\t --- 内层调用");
                    }
                }
            }
        }, "t1").start();
    }
}
